package org.android.bbox.data;

import org.android.bbox.AbstractActivity;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

//thanks to http://www.devx.com/wireless/Article/41133
public class ProfilProvider extends ContentProvider
{
	public static final String _ID = "id";
	public static final String PROVIDER_NAME = "org.android.bbox.data.ProfilProvider";
	public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/profils");
	private static final int PROFIL = 1;
	private static final int PROFIL_ID = 2;

	private SQLiteDatabase profilDB;

	private static final UriMatcher uriMatcher;

	static
	{
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(PROVIDER_NAME, "profils", PROFIL);
		uriMatcher.addURI(PROVIDER_NAME, "profils/#", PROFIL_ID);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs)
	{
		int count = 0;
		switch (uriMatcher.match(uri))
		{
			case PROFIL:
				count = this.profilDB.delete(ProfilDb.DATABASE_TABLE, selection, selectionArgs);
				break;
			case PROFIL_ID:
				count = this.profilDB.delete(ProfilDb.DATABASE_TABLE, _ID + " = " + uri.getPathSegments().get(1)
						+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
				break;
			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri)
	{
		switch (uriMatcher.match(uri))
		{
			// ---get all profil---
			case PROFIL:
				return "vnd.android.cursor.dir/" + PROVIDER_NAME;
			// ---get one profile---
			case PROFIL_ID:
				return "vnd.android.cursor.item/" + PROVIDER_NAME;
			default:
				throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values)
	{
		// ---add a new profil---
		long rowID = this.profilDB.insert(ProfilDb.DATABASE_TABLE, "", values);

		// ---if added successfully---
		if (rowID > 0)
		{
			Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate()
	{
		ProfilDb dbHelper = new ProfilDb(this.getContext());
		this.profilDB = dbHelper.getWritableDatabase();
		return (this.profilDB == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
	{

		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(ProfilDb.DATABASE_TABLE);

		// ---if getting a particular profil---
		if (uriMatcher.match(uri) == PROFIL_ID)
			sqlBuilder.appendWhere(_ID + " = " + uri.getPathSegments().get(1));

		if (sortOrder == null || sortOrder == "")
			sortOrder = "name";

		Cursor c = sqlBuilder.query(this.profilDB, projection, selection, selectionArgs, null, null, sortOrder);

		// ---register to watch a content URI for changes---
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
	{
		int count = 0;
		switch (uriMatcher.match(uri))
		{
			case PROFIL:
				count = this.profilDB.update(ProfilDb.DATABASE_TABLE, values, selection, selectionArgs);
				break;
			case PROFIL_ID:
				count = this.profilDB.update(ProfilDb.DATABASE_TABLE, values, _ID + " = " + uri.getPathSegments().get(1)
						+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
				break;
			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	private class ProfilDb extends SQLiteOpenHelper
	{
		public static final String DATABASE_TABLE = "profils";
		private static final int DATABASE_VERSION = 1;

		public ProfilDb(Context context)
		{
			super(context, AbstractActivity.DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (id INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ "name VARCHAR(60) NOT NULL, ip VARCHAR(15) NOT NULL," + "login VARCHAR(60) NOT NULL,"
					+ "password VARCHAR(60) DEFAULT NULL, password_user VARCHAR(60) DEFAULT NULL,"
					+ "save_password BOOLEAN DEFAULT FALSE, image VARCHAR(120) DEFAULT NULL, color CHAR(6) DEFAULT NULL;");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			Log.w("ProfileProvider", "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}
}
